package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.ProjectInfoListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DictionaryTreeContent;
import com.isunland.managesystem.entity.ProjectCollectOriginal;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2016/6/14 13:08
 */
public class ProjectChooseListFragment extends BaseListFragment {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.ProjectChooseListFragment.EXTRA_CONTENT";
  private static final int REQUIRE_DATA = 0;
  private static final int REQUIRE_STAGE = 1;
  private ProjectInfoListAdapter mAdapter;
  private ArrayList<ProjectCollectOriginal.ProjectCollectContent> mlist;
  private int mPage = 1;
  private EditText etprojectName;
  private TextView tvregDate;

  private String projectName = "";
  private String regDate = "";
  private String regDateName = "";
  private String type = "";

  //开始是否加载和显示空视图
  @Override protected void isPostStart(boolean isPostStart, boolean isShowEmpty) {
    super.isPostStart(false, false);
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    setTitleCustom("项目选择");
    //获取查询日期
    volleyGetDate();
  }

  private void volleyGetDate() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DATA_DICTIONARY_LIST);
    HashMap<String, String> params = new HashMap<>();
    params.put("dictFlg", "regDate");
    params.put("andriodUser", "true");
    params.put("memCode", mCurrentUser.getMemberCode());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        DictionaryTreeContent[] dataList = new Gson().fromJson(arg0, DictionaryTreeContent[].class);
        regDate = dataList[dataList.length - 2].getCustomAttrs();
        regDateName = dataList[dataList.length - 2].getName();
        tvregDate.setText(regDateName);
        volleyPost();
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.wrong_data);
      }
    });
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_project, null, false);

    tvregDate = (TextView) header.findViewById(R.id.tv_search_date);
    tvregDate.setInputType(InputType.TYPE_NULL);
    tvregDate.setTextIsSelectable(true);
    etprojectName = (EditText) header.findViewById(R.id.et_search_project);
    ImageSpan imageHint = new ImageSpan(mActivity, R.drawable.ic_search_gray_64);
    SpannableString spannableString = new SpannableString("   请输入项目名称");
    spannableString.setSpan(imageHint, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    etprojectName.setHint(spannableString);
    tvregDate.setOnClickListener(new View.OnClickListener() {

      @Override public void onClick(View v) {
        DialogFragment dialog =
            ProjectPropertyDialogFrament.newInstance(ProjectPropertyDialogFrament.regDate);
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(ProjectChooseListFragment.this, REQUIRE_DATA);
        dialog.show(fm, "");
      }
    });
    mListview.addHeaderView(header);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_query, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:

        getActivity().finish();
        return true;
      case R.id.menu_item_query:
        projectName = etprojectName.getText().toString();
        volleyPost();

        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override public String getUrl() {
    return ApiConst.ULR_PROJECT_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("projectName", projectName);
    params.put("regDate", regDate);
    params.put("page", "1");
    params.put("rows", "1000");
    return params;
  }

  @Override public void resolveResponse(String json) {
    ProjectCollectOriginal original = new Gson().fromJson(json, ProjectCollectOriginal.class);
    ArrayList<ProjectCollectOriginal.ProjectCollectContent> rows = original.getRows();
    if (mlist == null) {
      mlist = new ArrayList<>();
    }
    mlist.clear();
    mlist.addAll(rows);
    setAdapter(mlist);
  }

  private void setAdapter(ArrayList<ProjectCollectOriginal.ProjectCollectContent> mlist2) {
    if (mAdapter == null) {
      mAdapter = new ProjectInfoListAdapter(mActivity, mlist2);
    }
    setListAdapter(mAdapter);
    ((ProjectInfoListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    ProjectCollectOriginal.ProjectCollectContent content = mlist.get(position - 2);
    Intent i = new Intent();
    i.putExtra(EXTRA_CONTENT, content);
    getActivity().setResult(Activity.RESULT_OK, i);
    getActivity().finish();

    super.onListItemClick(l, v, position, id);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    volleyPost();
    super.onRefresh(refreshView);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUIRE_DATA) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      regDateName = customer.getName();
      regDate = customer.getId();
      ImageSpan imageHint = new ImageSpan(mActivity, R.drawable.ic_search_gray_64);
      SpannableString spannableString =
          new SpannableString(MyStringUtil.connect("   ", regDateName));
      spannableString.setSpan(imageHint, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
      tvregDate.setHint(spannableString);
    }
    if (requestCode == REQUIRE_STAGE) {
      volleyPost();
    }

    super.onActivityResult(requestCode, resultCode, data);
  }
}
